/**
 * mapvgl 地图服务
 * 用于初始化地图和处理地图相关功能
 */
import AMapLoader from '@amap/amap-jsapi-loader';

// 地图及图层实例
let map = null;
let mapvgl = null;
let layer = null;
let flylineLayer = null;
let pulseLineLayer = null;
let pointLayer = null;

// 动态加载mapvgl
const loadMapvgl = async () => {
  try {
    const mapv = await import('mapvgl');
    return mapv.default || mapv;
  } catch (error) {
    console.error('无法加载mapvgl', error);
    return null;
  }
};

// 动态加载mapvgl threelayers
const loadMapvThreeLayers = async () => {
  try {
    const mapvThree = await import('mapvgl/dist/mapvgl.threelayers.min.js');
    return mapvThree.default || mapvThree;
  } catch (error) {
    console.error('无法加载mapvgl threelayers', error);
    return null;
  }
};

/**
 * 初始化地图
 * @param {string} containerId 地图容器ID
 * @param {object} options 地图配置选项
 * @returns {Promise<object>} 地图实例
 */
export async function initMap(containerId, options = {}) {
  try {
    // 默认配置项
    const defaultOptions = {
      zoom: 4,
      center: [116.397428, 39.90923],
      mapStyle: 'amap://styles/dark',
      viewMode: '3D',
      pitch: 25,
      rotation: 0
    };

    // 合并配置
    const mergedOptions = { ...defaultOptions, ...options };

    // 加载高德地图API
    const AMap = await AMapLoader.load({
      key: '您的高德地图API Key', // 请替换为您自己的API Key
      version: '2.0',
      plugins: ['AMap.Scale', 'AMap.ToolBar', 'AMap.MapType', 'Map3D']
    });

    // 创建地图实例
    map = new AMap.Map(containerId, mergedOptions);

    // 添加地图控件
    map.addControl(new AMap.Scale());
    map.addControl(new AMap.ToolBar());

    // 尝试加载mapvgl
    const mapv = await loadMapvgl();
    
    // 如果mapvgl加载成功，初始化视图
    if (mapv) {
      try {
        mapvgl = new mapv.View({
          map: map
        });
      } catch (err) {
        console.error('初始化mapvgl视图失败', err);
        mapvgl = null;
      }
    }

    return { map, mapvgl };
  } catch (error) {
    console.error('地图初始化失败', error);
    throw error;
  }
}

/**
 * 添加3D点图层
 * @param {Array} data 点数据
 * @param {Object} options 图层选项
 * @returns {Object} 图层实例
 */
export async function add3DPointLayer(data, options = {}) {
  if (!mapvgl) {
    console.warn('mapvgl未初始化，无法创建3D点图层');
    return null;
  }

  // 默认配置
  const defaultOptions = {
    size: 2,
    color: '#1de9b6',
    shape: 'circle',
    blend: 'lighter'
  };

  // 合并配置
  const mergedOptions = { ...defaultOptions, ...options };

  // 加载mapvgl
  const mapv = await loadMapvgl();
  if (!mapv) return null;

  // 创建图层
  try {
    pointLayer = new mapv.PointLayer(mergedOptions);
    pointLayer.setData(data);
    mapvgl.addLayer(pointLayer);
    return pointLayer;
  } catch (error) {
    console.error('创建3D点图层失败', error);
    return null;
  }
}

/**
 * 添加3D柱状图层
 * @param {Array} data 点数据
 * @param {Object} options 图层选项
 * @returns {Object} 图层实例
 */
export async function add3DBarLayer(data, options = {}) {
  if (!mapvgl) {
    console.warn('mapvgl未初始化，无法创建3D柱状图层');
    return null;
  }

  // 默认配置
  const defaultOptions = {
    shape: 'cylinder',
    color: '#00ffff',
    opacity: 0.8,
    heightField: 'value',
    minHeight: 20,
    maxHeight: 200
  };

  // 合并配置
  const mergedOptions = { ...defaultOptions, ...options };

  // 加载threelayers模块
  const mapvThree = await loadMapvThreeLayers();
  if (!mapvThree) {
    // 尝试使用普通点图层作为替代
    return await add3DPointLayer(data, {
      size: 5,
      color: mergedOptions.color
    });
  }

  // 创建图层
  try {
    const barLayer = new mapvThree.BarLayer(mergedOptions);
    barLayer.setData(data);
    mapvgl.addLayer(barLayer);
    return barLayer;
  } catch (error) {
    console.error('创建3D柱状图层失败', error);
    return null;
  }
}

/**
 * 添加飞线图层
 * @param {Array} data 线数据 [{from: [lng, lat], to: [lng, lat], count: number}]
 * @param {Object} options 图层选项
 * @returns {Object} 图层实例
 */
export async function addFlyLineLayer(data, options = {}) {
  if (!mapvgl) {
    console.warn('mapvgl未初始化，无法创建飞线图层');
    return null;
  }

  // 默认配置
  const defaultOptions = {
    color: '#FF8C00',
    textureColor: '#ffffff',
    textureWidth: 20,
    textureLength: 80,
    speed: 0.1,
    altitude: 0,
    lineWidth: 1
  };

  // 合并配置
  const mergedOptions = { ...defaultOptions, ...options };

  // 加载threelayers模块
  const mapvThree = await loadMapvThreeLayers();
  if (!mapvThree) {
    // 尝试使用ECharts实现飞线效果
    console.warn('无法加载mapvgl threelayers，使用普通线图层替代');
    const mapv = await loadMapvgl();
    if (!mapv) return null;
    
    try {
      flylineLayer = new mapv.LineLayer({
        color: mergedOptions.color,
        lineWidth: mergedOptions.lineWidth,
        blend: 'lighter'
      });
      flylineLayer.setData(data);
      mapvgl.addLayer(flylineLayer);
      return flylineLayer;
    } catch (error) {
      console.error('创建替代飞线图层失败', error);
      return null;
    }
  }

  // 创建图层
  try {
    flylineLayer = new mapvThree.FlyLineLayer(mergedOptions);
    flylineLayer.setData(data);
    mapvgl.addLayer(flylineLayer);
    return flylineLayer;
  } catch (error) {
    console.error('创建飞线图层失败', error);
    return null;
  }
}

/**
 * 添加脉冲线图层
 * @param {Array} data 线数据
 * @param {Object} options 图层选项
 * @returns {Object} 图层实例
 */
export async function addPulseLineLayer(data, options = {}) {
  if (!mapvgl) {
    console.warn('mapvgl未初始化，无法创建脉冲线图层');
    return null;
  }

  // 默认配置
  const defaultOptions = {
    color: 'rgba(25, 255, 225, 1)',
    lineWidth: 2,
    animateTime: 2000
  };

  // 合并配置
  const mergedOptions = { ...defaultOptions, ...options };

  // 加载threelayers模块
  const mapvThree = await loadMapvThreeLayers();
  if (!mapvThree) {
    // 尝试使用普通线图层作为替代
    const mapv = await loadMapvgl();
    if (!mapv) return null;
    
    try {
      pulseLineLayer = new mapv.LineLayer({
        color: mergedOptions.color,
        lineWidth: mergedOptions.lineWidth
      });
      pulseLineLayer.setData(data);
      mapvgl.addLayer(pulseLineLayer);
      return pulseLineLayer;
    } catch (error) {
      console.error('创建替代脉冲线图层失败', error);
      return null;
    }
  }

  // 创建图层
  try {
    pulseLineLayer = new mapvThree.PulseLineLayer(mergedOptions);
    pulseLineLayer.setData(data);
    mapvgl.addLayer(pulseLineLayer);
    return pulseLineLayer;
  } catch (error) {
    console.error('创建脉冲线图层失败', error);
    return null;
  }
}

/**
 * 添加标记点
 * @param {Array} data 标记数据
 * @param {Object} options 标记选项
 */
export function addMarkers(data, options = {}) {
  if (!map) {
    throw new Error('地图尚未初始化');
  }

  // 清除已有标记
  map.clearMap();

  // 创建标记点
  data.forEach(item => {
    // 根据类型设置不同颜色
    let color = options.defaultColor || '#67C23A'; // 默认绿色
    
    if (options.typeColors && item.type) {
      color = options.typeColors[item.type] || color;
    }

    // 创建标记点
    const marker = new AMap.Marker({
      position: item.value || item.position,
      title: item.name,
      icon: new AMap.Icon({
        // 使用圆形标记
        size: new AMap.Size(16, 16),
        image: 'data:image/svg+xml;base64,' + btoa(`
          <svg width="32" height="32" viewBox="0 0 32 32" xmlns="http://www.w3.org/2000/svg">
            <circle cx="16" cy="16" r="12" fill="${color}" stroke="white" stroke-width="2"/>
          </svg>
        `),
        imageSize: new AMap.Size(16, 16)
      }),
      offset: new AMap.Pixel(-8, -8)
    });

    // 添加到地图
    map.add(marker);

    // 添加信息窗体
    if (options.showInfoWindow !== false) {
      marker.on('mouseover', () => {
        const infoWindow = new AMap.InfoWindow({
          content: `<div style="padding: 8px;">${item.name}</div>`,
          offset: new AMap.Pixel(0, -20)
        });
        infoWindow.open(map, item.value || item.position);
      });
    }
  });
}

/**
 * 设置地图主题样式
 * @param {string} theme 主题名称 dark|normal|satellite
 */
export function setMapTheme(theme) {
  if (!map) {
    throw new Error('地图尚未初始化');
  }

  let mapStyle = 'amap://styles/normal';
  
  switch (theme) {
    case 'dark':
      mapStyle = 'amap://styles/dark';
      break;
    case 'satellite':
      mapStyle = 'amap://styles/satellite';
      break;
    default:
      mapStyle = 'amap://styles/normal';
  }

  map.setMapStyle(mapStyle);
}

/**
 * 销毁地图及图层
 */
export function destroyMap() {
  if (mapvgl) {
    if (pointLayer) {
      try {
        mapvgl.removeLayer(pointLayer);
      } catch (error) {
        console.warn('移除点图层失败', error);
      }
      pointLayer = null;
    }
    
    if (flylineLayer) {
      try {
        mapvgl.removeLayer(flylineLayer);
      } catch (error) {
        console.warn('移除飞线图层失败', error);
      }
      flylineLayer = null;
    }
    
    if (pulseLineLayer) {
      try {
        mapvgl.removeLayer(pulseLineLayer);
      } catch (error) {
        console.warn('移除脉冲线图层失败', error);
      }
      pulseLineLayer = null;
    }
    
    mapvgl = null;
  }
  
  if (map) {
    map.destroy();
    map = null;
  }
} 